import { format } from 'date-fns';

const DATE_TIME_FORMAT = 'YYYY-MM-DD HH:mm';
const DATE_FORMAT = 'YYYY-MM-DD ';

export function formatToDateTime(date: any, formatStr = DATE_TIME_FORMAT): string {
  return format(date, formatStr);
}

export function formatToDate(date: any, formatStr = DATE_FORMAT): string {
  return format(date, formatStr);
}

export function msToTime(duration) {
  let seconds: any = Math.floor((duration / 1000) % 60),
    minutes: any = Math.floor((duration / (1000 * 60)) % 60),
    hours: any = Math.floor(duration / (1000 * 60 * 60));

  hours = hours < 10 ? '0' + hours : hours;
  minutes = minutes < 10 ? '0' + minutes : minutes;
  seconds = seconds < 10 ? '0' + seconds : seconds;

  return hours + ':' + minutes + ':' + seconds;
}

export function getDateStr(addDayCount) {
  const dd = new Date();

  dd.setDate(dd.getDate() + addDayCount); //获取AddDayCount天后的日期

  const y = dd.getFullYear();

  const m = dd.getMonth() + 1; //获取当前月份的日期

  const d = dd.getDate();

  return y + '-' + (m < 10 ? '0' + m : m) + '-' + (d < 10 ? '0' + d : d);
}

export function disablePreviousDate(startDate, endDate) {
  const currentDate = new Date();
  // 如果结束日期晚于当前时间，则禁用
  if (endDate && endDate > currentDate) return true;

  // 如果开始日期晚于当前时间，则禁用
  if (startDate && startDate > currentDate) return true;

  return false; // 其他情况下不禁用
}

export function disablePreviousDate2(startDate, endDate) {
  const currentDate = new Date(`${getDateStr(0)} 23:59:59`);
  // 如果结束日期晚于当前时间，则禁用
  if (endDate && endDate > currentDate) return true;

  // 如果开始日期晚于当前时间，则禁用
  if (startDate && startDate > currentDate) return true;

  return false; // 其他情况下不禁用
}

// 日期格式化
export function parseTime(time, pattern) {
  if (arguments.length === 0 || !time) {
    return null;
  }
  const format = pattern || '{y}-{m}-{d} {h}:{i}:{s}';
  let date;
  if (typeof time === 'object') {
    date = time;
  } else {
    if (typeof time === 'string' && /^[0-9]+$/.test(time)) {
      time = parseInt(time);
    } else if (typeof time === 'string') {
      time = time
        .replace(new RegExp(/-/gm), '/')
        .replace('T', ' ')
        .replace(new RegExp(/\.[\d]{3}/gm), '');
    }
    if (typeof time === 'number' && time.toString().length === 10) {
      time = time * 1000;
    }
    date = new Date(time);
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay(),
  };
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key];
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value];
    }
    if (result.length > 0 && value < 10) {
      value = '0' + value;
    }
    return value || 0;
  });
  return time_str;
}
